package com.git;

import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.Instant;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/version")
@RequiredArgsConstructor
public class VersionController {

    private final VersionInfo versionInfo;

    @GetMapping
    public ResponseEntity<Map<String, String>> getVersionInfo() {
        Map<String, String> response = new HashMap<>();
        response.put("version", versionInfo.getVersion());
        response.put("timestamp", Instant.now().toString());
        return ResponseEntity.ok(response);
    }

    @GetMapping("/changelog")
    public ResponseEntity<String> getChangelog() {
        return ResponseEntity.ok(versionInfo.getChangelog());
    }

    @GetMapping("/full")
    public ResponseEntity<Map<String, Object>> getFullVersionInfo() {
        Map<String, Object> response = new HashMap<>();
        response.put("version", versionInfo.getVersion());
        response.put("changelog", parseChangelog(versionInfo.getChangelog()));
        response.put("buildTime", Instant.now().toString());

        return ResponseEntity.ok(response);
    }

    private List<Map<String, String>> parseChangelog(String changelog) {
        // 简单的 changelog 解析逻辑
        List<Map<String, String>> changes = new ArrayList<>();
        if (changelog != null) {
            String[] lines = changelog.split("\n");
            for (String line : lines) {
                if (line.trim().startsWith("*") || line.trim().startsWith("-")) {
                    Map<String, String> change = new HashMap<>();
                    change.put("type", "change");
                    change.put("description", line.trim().substring(1).trim());
                    changes.add(change);
                }
            }
        }
        return changes;
    }
}
